import { ITools } from '@/utils/interface/ITools';

class Tools implements ITools {
  constructor() {}

  public primeNumber(n: number): number[] {
    if (n <= 1) return []; // 0和1不是质数
    let primes = [2]; // 2是最小的质数
    for (let num = 3; num <= n; num += 2) {
      // 从3开始，步长为2，因为除了2以外的偶数都不是质数
      let isPrime = true;
      for (let i = 2; i < primes.length; i++) {
        if (num % primes[i] === 0) {
          isPrime = false;
          break;
        }
        // 如果这个数已经被之前所有小于它的质数都除不尽，那么只需要检查到sqrt(num)即可
        // 因为如果num有一个因子大于sqrt(num)，那么它必定还有一个小于或等于sqrt(num)的因子
        // if (primes[i] * primes[i] > num) {
        //   break;
        // }
      }
      if (isPrime) {
        primes.push(num);
      }
    }
    return primes;
  }

  public isPalindrome = (str: string): boolean => {
    let i = 0;
    let j = str.length - 1;
    while (i < j) {
      const left = str[i].toLowerCase();
      const right = str[j].toLowerCase();

      if (!(left >= 'a' && left <= 'z') || (left >= '0' && left <= '9')) {
        i++;
      } else if (
        !(right >= 'a' && right <= 'z') ||
        (right >= '0' && right <= '9')
      ) {
        j--;
      } else if (left === right) {
        i++;
        j--;
      } else {
        return false;
      }
    }

    return true;
  };

  public *walk(version: string): Generator<string, void, unknown> {
    let part = '';
    let terminals: string[] = ['.', '-', '+']; // 终结符
    for (let i = 0; i < version.length; i++) {
      // 判断当前字符是包含终结符
      if (terminals.includes(version[i])) {
        yield part;
        part = '';
      } else {
        part += version[i];
      }
    }

    if (part) {
      yield part;
    }
  }
}

const tools = new Tools();
export default tools;
